from django.shortcuts import render
from apps.verifications.libs.captcha.captcha import captcha
from apps.verifications.libs.yuntongxun.ccp_sms import CCP
# from celery_tasks.sms.tasks import ccp_send_sms_code
import random, logging
logger = logging.getLogger('django')

from django.views import View
from django_redis import get_redis_connection
from django import http
from apps.verifications.libs.captcha.captcha import captcha
import logging, json, re
# Create your views here.
class ImageCodeView(View):
    """图形验证码
    GET http://www.meiduo.site:8000/image_codes/550e8400-e29b-41d4-a716-446655440000/
    """

    def get(self, request):

        # json_dict = json.loads(request.body.decode())
        # request.GET.get()
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')

        if not all([cur,pre]):
            return http.JsonResponse({'errno': 4001, 'errmsg':'缺少必传参数'})


        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存图形验证码
        # 使用配置的redis数据库的别名，创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')

        redis_conn.setex('img_%s' % cur, 300, text)
        redis_conn.delete('img_%s' % pre, 300, text)
        # print(image)
        # 响应图形验证码: image/jpg
        return http.HttpResponse(image, content_type='image/jpg')
        # return http.HttpResponse(image)

class SMSCodeView(View):
    """短信验证码
    GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
    """

    def post(self, request):
        # 提取参数
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        id = data_dict.get('id')
        text = data_dict.get('text')

        # 校验参数
        if not all([text, id, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 创建链接redis对象
        redis_conn = get_redis_connection('verify_code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % id)
        if image_code_server is None:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码失效'})
        # 删除图形验证码，避免恶意测试
        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()

        if text.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400, 'errmsg': '输入图形验证码有误'})

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 保存短信验证码，设置有效期
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)

        # 发送短信验证码
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 响应结果
        return http.JsonResponse({'errno': 0, 'errmsg': '发送短信成功'})


